package com.wishwall.auth;

import java.io.IOException;

import javax.persistence.EntityNotFoundException;

import com.sun.servicetag.UnauthorizedAccessException;
import com.wishwall.beans.DeviceBean;
import com.wishwall.exceptions.WishWallException;
import com.wishwall.persistence.PersistenceContext;

public class DeviceContext {

	/**
	 * 
	 * @param persistenceContext
	 * @param userAgent
	 * @param from
	 * @return
	 * @throws IOException
	 * @throws WishWallException
	 */
	public static DeviceContext createDeviceContext(PersistenceContext persistenceContext, 
			String userAgent,
			String deviceUid) 
			throws IOException, WishWallException {
			
		DeviceContext context = new DeviceContext();
		
		if (userAgent != null) {
			try {
				String[] applicationInfo = userAgent.split("/");
				context.applicationName = applicationInfo[0];
				context.applicationVersion = applicationInfo[1];
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if (deviceUid != null) {
			DeviceBean device = null;		
			try {
				device = persistenceContext.getDeviceManager().getDeviceByUID(deviceUid);
			} catch (EntityNotFoundException e) {
				device = null;
			}
			if (device == null) {
				throw new UnauthorizedAccessException("Invalid Device!");
			}
			context.device = device;
		}
		return context;				
	}
	
	
	
	//---------------------------------------------------------------------------------------------
	
	private String applicationName = null;
	private String applicationVersion = null;
	private DeviceBean device = null;
	
	/**
	 * 
	 * @return
	 */
	public String getApplicationName() {
		return applicationName;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getApplicationVersion() {
		return applicationVersion;
	}
	
	/**
	 * 
	 * @return
	 */
	public DeviceBean getDevice() {
		return device;
	}
	

}
